package com.yan.common.util;

import java.util.Arrays;
import java.util.List;

/**
 * 文件名清理工具类，验证文件名是否合法
 * 系统保留名字替换成test
 * 非法字符串替换成_
 * 文件名长度超过255截取255个字符
 *
 * @author yanchen
 */
public class FilenameSanitizer {

    private static final List<String> RESERVED_NAMES = Arrays.asList(
        "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5",
        "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", 
        "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
    );
    private static final  String REPLACE_CHAR = "_";
    private static final  String REPLACE_STRING = "test";
    public static String sanitizeFilename(String filename) {
        // 处理空输入
        if (filename == null || filename.trim().isEmpty()) {
            return REPLACE_STRING;
        }

        // 步骤1: 替换非法字符和控制字符
        StringBuilder sanitized = new StringBuilder();
        for (char c : filename.toCharArray()) {
            sanitized.append(isInvalidChar(c) ? REPLACE_CHAR : c);
        }

        // 步骤2: 处理结尾的空格或点
        String processed = sanitized.toString();
        processed = processed.replaceAll("[. ]+$", REPLACE_CHAR);

        // 步骤3: 分割主文件名和扩展名
        String[] parts = processed.split("\\.", 2);
        String mainName = parts[0];
        String extension = parts.length > 1 ? parts[1] : "";

        // 步骤4: 处理保留名称和空主文件名
        if (mainName.isEmpty() || isReservedName(mainName)) {
            mainName = REPLACE_STRING;
        }

        // 重组文件名
        String result = mainName + (extension.isEmpty() ? "" : "." + extension);

        // 步骤5: 再次验证结尾和长度
        result = result.replaceAll("[. ]+$", REPLACE_CHAR);
        if (result.length() > 255) {
            result = result.substring(0, 255);
        }
        return result.isEmpty() ? "test" : result;
    }

    private static boolean isInvalidChar(char c) {
        return c < 0x20 || "\\/:*?\"<>|".indexOf(c) != -1;
    }

    private static boolean isReservedName(String name) {
        return RESERVED_NAMES.contains(name.toUpperCase());
    }


}